// roleManage.js
import {
  Button,
  Form,
  Input,
  Popconfirm,
  Divider,
  Table,
  Typography,
  Select,
  Space,
  Modal,
  message,
  DatePicker,
  InputNumber,
  Radio,
} from "antd";
// import { useNavigate } from "react-router-dom";
import React, { useState, useEffect } from "react";
import { observer } from "mobx-react";
import store from "../../../store";
// import { ConsoleSqlOutlined } from '@ant-design/icons';

// import Jiamenggl from '../../../store/JiaMeng'
// import './index.scss'
const { Option } = Select;
const { JiaMenggl } = store;
// const JiaMeng = [
//     // {
//     //     key: '1',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨过',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },
//     // {
//     //     key: '2',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨紫',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },
//     // {
//     //     key: '3',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨无敌',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },
//     // {
//     //     key: '4',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨馨陌',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },
//     // {
//     //     key: '5',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨昊',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },
//     // {
//     //     key: '6',
//     //     roleName: '杭州西湖分店',
//     //     address:'成都市正熙街内',
//     //     contacts:'杨龙',
//     //     numbers:'1351132356',
//     //     order:'280',
//     //     amountMoney:'455643.243',
//     //     commission:'5%',
//     //     numbergoos:'856564',
//     //     Mcode:'M349325',
//     //     status: '正常',
//     //     members:'66',
//     //     creatTime: '2017-05-28',

//     // },

// ];

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode =
    inputType === "number" ? (
      <Select>
        <Option value="正常">正常</Option>
        <Option value="冻结">冻结</Option>
      </Select>
    ) : (
      <Input />
    );
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `请填写 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const Jiameng = () => {
  // const savesos = useNavigate();
  const [count, setCount] = useState(JiaMenggl.JiaMengData.length + 1);
  const createRole = () => {
    // let date = new Date();
    // let years = date.getFullYear();
    // let month = date.getMonth();
    // month = month > 9 ? month : "0" + month;
    // let days = date.getDate();
    // days = days > 9 ? days : "0" + days;
    // let detailTime = date.toLocaleTimeString();
    // let time = years + "-" + month + "-" + days + " " + detailTime;
    // const newData = {
    //   key: count,
    //   roleName: "杭州西湖分店",
    //   address: "成都市正熙街内",
    //   contacts: "杨龙",
    //   numbers: "1351132356",
    //   order: "280",
    //   amountMoney: "455643.243",
    //   commission: "5%",
    //   numbergoos: "856564",
    //   Mcode: "M349325",
    //   status: "正常",
    //   members: "66",
    //   creatTime: "2017-05-28",
    // };
    setCount(count + 1);
    // setData([...data, newData]);
  };
  const [form] = Form.useForm();
  const [data, setData] = useState(JiaMenggl.JiaMengData);

  const [editingKey, setEditingKey] = useState("");
  const isEditing = (record) => record.key === editingKey;
  const edit = (record) => {
    form.setFieldsValue({
      // key: "",
      // franchiseeName: "",
      // storeAddress: "",
      // status: "",
      ...record,
    });
    setEditingKey(record.key);
  };
  const cancel = () => {
    setEditingKey("");
  };
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      
      // console.log(key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        console.log(newData[index]);
        setEditingKey("");
      } 
      else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
      newData[0].id = key
      // console.log(newData);
      JiaMenggl.xiugaidadet(newData[0])
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };
  const columns = [
    {
      title: "序号",
      dataIndex: "id",
      editable: false,
    },
    {
      title: "加盟商名称",
      dataIndex: "franchiseeName",
      editable: true,
      width: "10%",
    },
    {
      title: "门店地址",
      dataIndex: "storeAddress",
      editable: true,
    },
    {
      title: "联系人",
      dataIndex: "contactsName",
      editable: true,
      width: "6%",
    },
    {
      title: "联系电话",
      dataIndex: "contactsPhone",
      editable: true,
    },
    {
      title: "订单数",
      dataIndex: "orderQuantity",
      editable: true,
    },
    {
      title: "销售金额",
      dataIndex: "salesAmount",
      editable: true,
    },
    {
      title: "佣金比例",
      dataIndex: "commissionRate",
      editable: true,
    },
    {
      title: "结算金额",
      dataIndex: "settlementAmount",
      editable: true,
    },
    {
      title: "M码",
      dataIndex: "mcode",
      editable: true,
    },
    {
      title: "状态",
      dataIndex: "status",
      editable: true,
      width: "5%",
    },
    {
      title: "关联会员数",
      dataIndex: "mebership",
      editable: true,
    },
    {
      title: "录入时间",
      dataIndex: "inputTime",
      editable: false,
    },
    {
      title: "操作",
      width: "10%",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              保存
            </Typography.Link>
            <Popconfirm
              title="确定取消编辑?"
              onConfirm={cancel}
              okText="是"
              cancelText="否"
            >
              <span style={{ cursor: "pointer" }}>取消</span>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ""}
            onClick={() => edit(record)}
          >
            编辑
          </Typography.Link>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "status" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  const NOtext = () => {
    message.success("已取消添加！");
  };
  const key = "updatable";
const [formData,setFormData] = useState({})
  const openMessage = () => {
    JiaMenggl.tianjiadadet(formData);
    message.loading({ content: "添加中...", key });
    setTimeout(() => {
      message.success({ content: "添加成功!", key, duration: 2 });
      createRole();
    }, 1000);
  };
  const [open, setOpen] = useState(false);
  const query = () => {
    setOpen(false);
    // console.log(111);
    openMessage();
  };
  const nodess = () => {
    setOpen(false);
    NOtext();
  };

  const [componentSize, setComponentSize] = useState("default");
  const onFormLayoutChange = ({ size }) => {
    setComponentSize(size);
  };

  const { Option } = Select;
  const handleChange = (value) => {
    console.log(value);
  };
  useEffect(() => {
    // JiaMenggl.showAllFran1();
    if (JiaMenggl.JiaMengData.length === 0) {
      JiaMenggl.showAllFran1();
    }
  }, []);
  const onFinish = (value) => {
    // console.log(value);
    setFormData(value)
  };

  return (
    <>
      <Form>
        <Space size={"middle"}>
          <Form.Item label="加盟商名称" name="franchiseeName">
            <Input placeholder="加盟商名称" style={{ width: 100 }} />
          </Form.Item>
          <Form.Item label="联系人" name="contactsName">
            <Input placeholder="联系人" style={{ width: 100 }} />
          </Form.Item>
          <Form.Item label="联系电话" name="contactsPhone">
            <Input placeholder="联系电话" style={{ width: 100 }} />
          </Form.Item>
          <Form.Item label="M码" name="mcode">
            <Input placeholder="M码" style={{ width: 100 }} />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select placeholder="请选择" style={{ width: 120 }}>
              <Option value="正常">正常</Option>
              <Option value="冻结">冻结</Option>
            </Select>
          </Form.Item>
        </Space>
        <Button className="btn" style={{ width: 100, marginLeft: 30 }}>
          搜索
        </Button>
      </Form>
      <Divider />
      <Button className="btn" onClick={() => setOpen(true)}>
        添加加盟商
      </Button>
      <Button className="btn">导出</Button>
      <Form form={form} component={false}>
        {/* 表格 */}
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={JiaMenggl.JiaMengData}
          columns={mergedColumns}
          rowKey={(record) => record.id}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
            pageSize: 5,
          }}
        />

        <Modal
          title="添加加盟商"
          centered
          open={open}
          onOk={query}
          onCancel={nodess}
          width={1000}
          okText="确定"
          cancelText="取消"
          htmlType="submit"
        >
          <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 14,
            }}
            layout="horizontal"
            initialValues={{
              size: componentSize,
            }}
            onValuesChange={onFormLayoutChange}
            size={componentSize}
            onFinish={onFinish}
          >
            <Form.Item label="大小样式" name="size">
              <Radio.Group>
                <Radio.Button value="small">小</Radio.Button>
                <Radio.Button value="default">中</Radio.Button>
                <Radio.Button value="large">大</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="加盟商名称" name='franchiseeName'>
              <Input />
            </Form.Item>
            <Form.Item label="门店地址" name='storeAddress'>
              <Input />
            </Form.Item>
            <Form.Item label="联系人" name='contactsName'>
              <Input />
            </Form.Item>
            <Form.Item label="联系电话" name='contactsPhone'>
              <Input />
            </Form.Item>
            <Form.Item label="佣金比例" name='commissionRate'>
              <Input />
            </Form.Item>
            <Form.Item label="M码" name='M码'>
              <Input />
            </Form.Item>
            <Form.Item label="状态" name='status'>
              <Select
                labelInValue
                defaultValue={{
                  value: "status",
                  label: "请选择",
                }}
                style={{ width: "100%" }}
                onChange={handleChange}
              >
                <Option value="jack">正常</Option>
                <Option value="lucy">冻结</Option>
              </Select>
            </Form.Item>
            <Form.Item label="录入时间" name='inputTime'>
              <DatePicker style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="订单数" name='orderQuantity'>
              <InputNumber prefix="￥" style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item wrapperCol={{ span: 12, offset: 6 }} >
              <Button type="primary" >
                提交
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Form>
    </>
  );
};
export default observer(Jiameng);
